import fs from 'fs'
import path from 'path'
import {contextBridge, ipcRenderer, IpcRenderer} from 'electron'
import {domReady} from './utils'
import {useLoading} from './loading'
import remote from './remote';
import store from "./store";
import file from './file'
import music from './music'

const isDev = process.env.NODE_ENV === 'development'
const {removeLoading, appendLoading} = useLoading()

domReady().then(() => {
    appendLoading()
})


// --------- Expose some API to Renderer process. ---------
contextBridge.exposeInMainWorld('removeLoading', removeLoading)
contextBridge.exposeInMainWorld('remote', remote);
contextBridge.exposeInMainWorld('store', store);
contextBridge.exposeInMainWorld('$file', file);
contextBridge.exposeInMainWorld('music', music);
contextBridge.exposeInMainWorld('node', {fs: withPrototype(fs), path: withPrototype(path)})

// `exposeInMainWorld` can not detect `prototype` attribute and methods, manually patch it.
function withPrototype(obj: Record<string, any>) {
    const props = Object.getPrototypeOf(obj)
    for (const [key, value] of Object.entries(props)) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) continue
        if (typeof value === 'function') {
            // Some native API not work in Renderer-process, like `NodeJS.EventEmitter['on']`. Wrap a function patch it.
            obj[key] = function (...args: any) {
                return value.call(obj, ...args)
            }
        } else {
            obj[key] = value
        }
    }
    return obj
}
